package com.sr.wslr.front.cfg;


import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.cache.interceptor.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

@Configuration
@EnableCaching
public class CachingConfig implements CachingConfigurer {

	@Autowired
    RedisOperations<Object, Object> redisTemplate;

	@Bean(name="ehcache")
    @Override
    public CacheManager cacheManager() {
        EhCacheCacheManager cacheManager = new EhCacheCacheManager();
        cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
        return cacheManager;
    }

	@Bean(name="redis")
	public CacheManager redisCacheManger() {
		RedisCacheManager cacheManager = new RedisCacheManager((RedisTemplate<Object, Object>)redisTemplate);
		cacheManager.setUsePrefix(true);
		Map<String, Long> expires = Maps.newHashMap(); 
		expires.put("attachment", 2592000L);//缓存30天
		expires.put("hereInfo", 2592000L);//缓存30天
		expires.put("custInfo", 2592000L);//缓存30天
		expires.put("favor", 2592000L);//缓存30天
		cacheManager.setExpires(expires);
		return cacheManager;
	}
	
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        ehCacheManagerFactoryBean.setCacheManagerName("webCache");
        ehCacheManagerFactoryBean.setShared(true);
        return ehCacheManagerFactoryBean;
    }

	@Override
	public CacheResolver cacheResolver() {
		return new SimpleCacheResolver(cacheManager());
	}

	@Override
	public CacheErrorHandler errorHandler() {
		return new SimpleCacheErrorHandler();
	}

}
